module FamilyTreeApi
  module Person
    module Assertion
      
      class Base
        attr_reader :version, :contributor, :modified, :disputing, :citations
        attr_accessor :id, :changed, :notes, :tempId
        
        def initialize
          @notes = []
        end
        
        def parse_attributes(assertion_element)
          e = assertion_element
          @id = e.attributes["id"]
          @version = e.attributes["version"]
          @contributor = e.attributes["contributor"]
          @modified = e.attributes["modified"]
          @disputing = e.attributes["disputing"]
        end
        
        def state
          if @id.nil?
            :new
          else
            :clean
          end
        end
        
        def add_note(value)
          note = FamilyTreeApi::Person::Assertion::Note.new
          note.value = value
          @notes << note
        end
        
        def assertion_type
          self.class.to_s.split('::').last.downcase
        end
        
        def to_xml
          e = REXML::Element.new(assertion_type)
          e.add_attribute('id', @id) if @id
          e.add_attribute('version', @version) if @version
          e.add_attribute('modified', @modified) if @modified
          e.add_attribute('disputing', @disputing) if @disputing
          e.add_attribute('tempId', @tempId) if @tempId
          if @notes.size > 0
            notes = e.add_element('notes')
            @notes.each do |n|
              notes.add_element(n.to_xml)
            end
          end
          e
        end
        
        def self.parse_response(assertion_element)
          assertion = self.new
          assertion.id = assertion_element.attributes["id"]
          assertion.tempId = assertion_element.attributes["tempId"]
          assertion
        end

      end
      
      class Note
        attr_accessor :value, :id
        
        def to_xml
          e = REXML::Element.new('note')
          e.add_text(@value)
          e.add_attribute('id',@id) if @id
          e
        end
        
        def ==(other)
          @value == other.value &&
            @id == other.id
        end
      end
      
    end
  end
end
